package com.xaicode.auth.service.impl;

import cn.hutool.core.util.StrUtil;
import com.xaicode.auth.base.BaseMpServiceImpl;
import com.xaicode.auth.entity.SysDict;
import com.xaicode.auth.entity.SysDictDetail;
import com.xaicode.auth.mapper.SysDictMapper;
import com.xaicode.auth.security.domain.params.SysDictQueryParam;
import com.xaicode.auth.service.ISysDictDetailService;
import com.xaicode.auth.service.ISysDictService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SysDictServiceImpl extends BaseMpServiceImpl<SysDictMapper, SysDict> implements ISysDictService {

    @Autowired
    private ISysDictDetailService sysDictDetailService;


    @Override
    public PageInfo<SysDict> queryPage(SysDictQueryParam query) {
        startPage(query);
        List<SysDict> list = queryList(query);
        return PageInfo.of(list);
    }

    @Override
    public List<SysDict> queryList(SysDictQueryParam query) {
        LambdaQueryWrapper<SysDict> lqw = Wrappers.lambdaQuery();
        lqw.eq(StrUtil.isNotBlank(query.getDictKey()), SysDict::getDictKey, query.getDictKey());
        List<SysDict> list = list(lqw);
        return list;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateDict(SysDict entity) {
        updateById(entity);

        // 更新字典中冗余存储的dictKey
        sysDictDetailService.update(new LambdaUpdateWrapper<SysDictDetail>()
                .eq(SysDictDetail::getPid, entity.getId())
                .set(SysDictDetail::getDictKey, entity.getDictKey())
        );
    }

    @Override
    public void removeDictByIds(List<Integer> ids) {
        removeByIds(ids);

        // 删除关联字典详情
        sysDictDetailService.remove(new LambdaUpdateWrapper<SysDictDetail>()
                .in(SysDictDetail::getPid, ids)
        );
    }
}
